package homework;

import java.io.*;
import java.util.Properties;

/**
 * @author DCSGO
 * @version 1.0
 * (1)要编写一个dog.properties
 * name=tom
 * age=5
 * color=red
 * (2)编写Dog类(name,age,color)创建一个dog对象，读取dog.properties
 * 用相应的内容完
 * 成属性初始化并输出
 * (3)将创建的Dog对象序列化到文件 dog.dat 文件 再反序列化
 */
public class Homework03 {
    public static Dog getDog(String fileName) throws IOException, ClassNotFoundException {
        if (fileName == null) {
            return null;
        }
        ObjectInputStream ois = new ObjectInputStream(new FileInputStream(fileName));
        Object o = ois.readObject();
        ois.close();
        if (o instanceof Dog) {
            return (Dog) o;
        } else {
            throw new ClassCastException();
        }
    }

    public static void main(String[] args) throws IOException, ClassNotFoundException {
        Properties dogProperties = new Properties();
        String filePath = "src\\homework\\dog.properties";
        dogProperties.setProperty("name", "tom");
        dogProperties.setProperty("age", "5");
        dogProperties.setProperty("color", "red");
        dogProperties.store(new FileWriter(filePath), null);

        String name = dogProperties.getProperty("name");
        int age = Integer.parseInt(dogProperties.getProperty("age"));
        String color = dogProperties.getProperty("color");
        Dog dog = new Dog(name, age, color);
        System.out.println(dog);

        ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("src\\homework\\dog.dat"));
        oos.writeObject(dog);
        oos.close();
        System.out.println("dog序列化并保存成功");

        System.out.println("反序列化");
        System.out.println(getDog("src\\homework\\dog.dat"));
    }
}

class Dog implements Serializable {

    String name;
    int age;
    String color;

    @Override
    public String toString() {
        return "Dog{" +
                "name='" + name + '\'' +
                ", age=" + age +
                ", color='" + color + '\'' +
                '}';
    }

    public Dog(String name, int age, String color) {
        this.name = name;
        this.age = age;
        this.color = color;
    }
}
